<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Chat</title>
    <style>
        body { font-family: Arial, sans-serif; }
        #messages { border: 1px solid #ccc; height: 300px; overflow-y: auto; margin-bottom: 10px; padding: 10px; }
        #messageInput { width: 100%; padding: 10px; }
        button { padding: 10px; margin-top: 5px; }
        input[type="file"] { margin-top: 10px; }
    </style>
</head>
<body>
<h2>杰哥狗叫群</h2>
<div id="messages"></div>
<textarea id="messageInput" placeholder="开始狗叫..."></textarea><br>

<input type="file" id="imageInput" accept="image/*" /><br>

<button onclick="sendMessage()">狗叫</button>

<script>
    var socket = new WebSocket("ws://59.110.239.57:8080/chat");

    socket.onopen = function() {
        console.log("Connected to WebSocket");
    };

    socket.onmessage = function(event) {
        var message = event.data;
        var messagesDiv = document.getElementById("messages");

        // Check if the message is an image (Base64 format)
        if (message.startsWith("data:image")) {
            // Display the image
            messagesDiv.innerHTML += `<p><img src="${message}" width="200" /></p>`;
        } else {
            // Display a regular text message
            messagesDiv.innerHTML += `<p>${message}</p>`;
        }

        messagesDiv.scrollTop = messagesDiv.scrollHeight; // Scroll to the bottom
    };

    socket.onclose = function() {
        console.log("Disconnected from WebSocket");
    };

    function sendMessage() {
        var messageInput = document.getElementById("messageInput");
        var imageInput = document.getElementById("imageInput");
        var message = messageInput.value;

        if (message) {
            socket.send(message);  // Send text message
            messageInput.value = ''; // Clear input after sending
        }

        if (imageInput.files[0]) {
            var file = imageInput.files[0];

            // Check file type (extension) for valid image formats
            var validImageTypes = ["image/jpeg", "image/png", "image/webp", "image/gif"];

            if (validImageTypes.includes(file.type)) {
                var reader = new FileReader();
                reader.onloadend = function() {
                    var imageData = reader.result;
                    socket.send(imageData);  // Send image as binary data (Base64)
                    imageInput.value = ''; // Clear file input after sending
                };
                reader.readAsDataURL(file);  // Read image as Data URL
            } else {
                alert("Invalid file type. Please upload a JPG, PNG, WEBP, or GIF image.");
            }
        }
    }
</script>
</body>
</html>
